package com.jprocms.module.cms.job;

import com.jpro.framework.tenant.core.context.TenantContextHolder;
import com.jprocms.module.cms.constant.CmsSysConstants;
import com.jprocms.module.cms.dal.redis.RedisKeyConstants;
import com.jprocms.module.cms.framework.cache.CacheService;
import com.jprocms.module.cms.service.accesslog.AccessService;
import com.jprocms.module.cms.service.sitetpl.TplService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 定时任务
 *
 * @author jprocms
 */
@Slf4j
@Configuration
public class ScheduleConfig {
    private final AccessService accessService;
    private TplService tplService;
    private CacheService cacheService;

    private Long currLocalConfigTime = System.currentTimeMillis();

    public ScheduleConfig(AccessService accessService, TplService tplService, CacheService cacheService) {
        this.accessService = accessService;
        this.tplService = tplService;
        this.cacheService = cacheService;
    }

    /**
     * 将访问日志缓存写入数据库。使用随机的定时任务，以避免集群环境下所有机器同时写数据库。
     * 不需要集群。只在本机执行，而且每台机器都必须执行。
     */
    @Scheduled(cron = "#{new java.util.Random().nextInt(35) + 5} * * * * ?")
    public void flushVisitLogTask() {
        TenantContextHolder.setTenantId(CmsSysConstants.CMS_TENANT_ID);
        accessService.flushAccessLog();
    }

    /**
     * 检查 是否更新了系统配置
     */
    @Scheduled(cron = "#{new java.util.Random().nextInt(30) + 5} * * * * ?")
    public void checkConfigUpdate() {
        final Object cacheObject = cacheService.getCacheObject(RedisKeyConstants.CONFIG_UPDATE_TIME);
        if (cacheObject != null) {
            Long cacheConfigUpdateTime = (Long) cacheObject;
            if (cacheConfigUpdateTime > currLocalConfigTime) {
                tplService.initLocalCache();
                currLocalConfigTime = cacheConfigUpdateTime;
            }
        }
    }

}
